<template>
  <!--size抽屉宽度（或高度）  default 378px 和 large 736px -->
  <a-drawer
      v-model:open="visible"
      ref="employeeDetailModalRef"
      class="edit-drawer modal-fixed-bottom"
      root-class-name="root-customer-drawer"
      width="800px"
      :closable="false"
      @close="onClose"
  >
    <div class="closeable" @click="onClose">{{ $t('self.closeButton') }}</div>
    <div class="modal-header">{{ title }}</div>

    <a-form :model="formState" :rules="formRules" :label-col="labelCol" :wrapper-col="wrapperCol"
            @finish="onSubmit"
    >
        <a-spin :spinning="formLoading">
          <a-form-item :label="$t('self.user.modal.firstName')" name="firstName">
            <a-input allow-clear v-model:value="formState.firstName" placeholder="" />
          </a-form-item>
          <a-form-item :label="$t('self.user.modal.lastName')" name="lastName">
            <a-input allow-clear v-model:value="formState.lastName" placeholder="" />
          </a-form-item>
          <a-form-item :label="$t('self.systemUser.identificationNumber')" name="identificationNumber">
            <a-input allow-clear v-model:value="formState.identificationNumber" placeholder="" />
          </a-form-item>
                    <a-form-item :label="$t('self.systemUser.modal.col3')" name="mobile">
            <a-input allow-clear v-model:value="formState.mobile" placeholder="" />
          </a-form-item>
          <a-form-item :label="$t('self.user.tips9')" name="email">
            <a-input allow-clear v-model:value="formState.email" placeholder="" />
          </a-form-item>
                  <a-form-item :label="$t('self.businessStation.modal.col5')" name="address">
          <a-input allow-clear v-model:value="formState.address" placeholder="" />
        </a-form-item>

          <a-form-item :label="$t('self.systemUser.modal.col8')" name="name">
            <a-input allow-clear v-model:value="formState.name" placeholder="" />
          </a-form-item>
          <a-form-item :label="$t('self.systemUser.modal.col9')" name="password">
            <a-input allow-clear v-model:value="formState.password" placeholder="" type="password" />
          </a-form-item>
          <a-form-item :label="$t('self.systemUser.tips21')" name="roleIds">
            <a-select mode="multiple" v-model:value="formState.roleIds" :options="roleArrOptions" :fieldNames="{label: 'roleName',value: 'id'}" />
          </a-form-item>
          <a-form-item :label="$t('self.systemUser.assignedId')" name="assignedId">
            <a-input allow-clear v-model:value="formState.assignedId" placeholder="" />
          </a-form-item>

          <a-form-item :label="$t('self.user.modal.col14')" name="orgId">
            <a-select v-model:value="formState.orgId" :options="orgOptions" 
            :fieldNames="{label: 'orgName',value: 'id'}" 
            :placeholder="$t('self.pleaseChoose')" @change="onChangeOrg" />
         </a-form-item>

          <a-form-item :label="$t('self.systemUser.assignKeyfob')" name="assignKeyfob">
            <a-input allow-clear v-model:value="formState.assignKeyfob" placeholder="" />
          </a-form-item>
          <a-form-item :label="$t('self.systemUser.keyfobId')" name="keyfobId">
            <a-input allow-clear v-model:value="formState.keyfobId" placeholder="" />
          </a-form-item>

						<a-form-item name="countryAuthorize" :label="$t('self.stationMap.africaCountry')" >
							<a-select allow-clear v-model:value="formState.countryAuthorize" 
							:options="africaCountryOptions"   :field-names="{ label: 'display', value: 'value' }"  @change="handleAfricaCountryChange"
							:placeholder="$t('self.pleaseChoose')">
							</a-select>
						</a-form-item>

						<a-form-item name="authorizedCity" :label="$t('self.stationMap.africaTestType')">
							<a-select allow-clear v-model:value="formState.authorizedCity" 
							:options="africaTestTypeOptions"
  							:field-names="{ label: 'label', value: 'value' }" @change="handleAfricaTestTypeChange"
							:placeholder="$t('self.pleaseChoose')">
							</a-select>
						</a-form-item>





          <!-- <a-form-item :label="$t('self.operators.tips40')" name="country">
            <a-input allow-clear v-model:value="formState.country" placeholder="" />
          </a-form-item>
          <a-form-item :label="$t('self.operators.tips44')" name="city">
            <a-input allow-clear v-model:value="formState.city" placeholder="" />
          </a-form-item>



          <a-form-item :label="$t('self.businessStation.modal.col14')" name="vehicleType">
            <a-select
              v-model:value="formState.vehicleType"
              :options="priceTypeOptions"
              @change="selType"
              :disabled="mode === 'edit'"
            />
          </a-form-item>

          <a-form-item :label="$t('self.systemUser.tips22')" name="vehicleChassis">
            <a-input allow-clear v-model:value="formState.vehicleChassis" placeholder="" />
          </a-form-item>

          <a-form-item :label="$t('self.userBind.tips10')" name="plateNumber">
            <a-input allow-clear v-model:value="formState.plateNumber" placeholder="" />
          </a-form-item>

          <a-form-item :label="$t('self.userBind.tips19')" name="color">
            <a-input allow-clear v-model:value="formState.color" placeholder="" />
          </a-form-item>

          <a-form-item :label="$t('self.systemUser.tips23')" name="brandModel">
            <a-input allow-clear v-model:value="formState.brandModel" placeholder="" />
          </a-form-item>


          <a-form-item :label="$t('self.systemUser.keyfobType')" name="keyfobType">
            <a-input allow-clear v-model:value="formState.keyfobType" placeholder="" />
          </a-form-item>


          <a-form-item :label="$t('self.systemUser.keyfobColor')" name="keyfobColor">
            <a-input allow-clear v-model:value="formState.keyfobColor" placeholder="" />
          </a-form-item>

          <a-form-item :label="$t('self.systemUser.assignedUUID')" name="assignedUUID">
            <a-input allow-clear v-model:value="formState.mobile" placeholder="" />
          </a-form-item>

          <a-form-item :label="$t('self.systemUser.assignedKeyfob')" name="assignedKeyfob">
            <a-input allow-clear v-model:value="formState.assignedKeyfob" placeholder="" />
          </a-form-item> -->











        <a-form-item :label="$t('self.systemUser.modal.col6')" name="status">
          <a-select v-model:value="formState.status" :options="[{ label: $t('self.systemUser.tips9'), value: 1 },{ label: $t('self.systemUser.tips10'), value: 0 }]" />
        </a-form-item>
          <!-- <a-form-item label="Country of authorized" name="countryAuthorize">
            <a-select mode="multiple" showSearch v-model:value="formState.countryAuthorize" :options="countryAuthorizeOptions" :fieldNames="{label: 'paraDesc',value: 'key'}" :placeholder="$t('self.pleaseChoose')" />
          </a-form-item> -->
          <!--      <a-form-item :label="$t('self.systemUser.modal.col7')" name="orgId">-->
  <!--        <a-select v-model:value="formState.orgId" :options="orgOptions" :fieldNames="{label: 'orgName',value: 'id'}" />-->
  <!--      </a-form-item>-->

        </a-spin>

        <div class="base-flex base-rows base-align-items-center base-justify-content-center footer">
          <a-button type="primary" html-type="submit">{{ $t('self.submitButton') }}</a-button>
          <a-button class="base-ml10" @click="onClose">{{ $t('self.cancelButton') }}</a-button>
        </div>
      </a-form>


  </a-drawer>
</template>

<script setup>
import { computed, getCurrentInstance, onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
const { proxy } = getCurrentInstance()
const $TOOL = proxy.$TOOL
const $T = proxy.$t
const $API = proxy.$API
const emit = defineEmits(['close','ok'])
// import { VueCountryCode } from 'vue3-country-select'
// import 'vue3-country-select/style.css'
const visible = ref(false)
const formLoading = ref(false)
// 模式，add新增，show查看，edit编辑
const mode = ref('add')
const labelCol = {
  style: {
    width: '150px',
  },
};
const wrapperCol = {
  span: 16,
};
const priceTypeOptions = [
  { label: $T('self.businessStation.supportingFacilitiesType.tips1'), value: 1 },
  { label: $T('self.businessStation.supportingFacilitiesType.tips2'), value: 2 },
]
const title = ref()

import cityData from '@/config/data.js'
import dayjs from 'dayjs'
const cityRaw =  cityData.cityRaw
const formState = ref({
  "id": 0,
  "userType": 1,
  "realName": "",
  "name": "",
  "password": "",
  "status": 1,
  "mobile": "",
  "orgId": null,
  "roleIds": [], //
  "countryAuthorize": [], // 多个用逗号隔开
  // "africaCountry": null,    // 非洲国家编码
  // "africaCountryName": null, // 非洲国家名称
  "authorizedCountryCode": null,
  "authorizedCity": null, // 城市名称
  "address":null,
  "firstName":"",
  "lastName":"",
  "identificationNumber":"",
  "email":"",
  "keyfobId":"",
  "assignKeyfob":"",
  "assignedId":"",
  "operator":""//

  //firstName lastName email

// {"realName":"张三2","name":"zs22","password":"1111211","status":1,
// "mobile":"136555545422","orgId":"1",
// "fullData":"1","orgIds":["1"],"userType":1,
// "countryAuthorize":"Rwanda#250(单选)"
// ,"address":"1","assignedId":"2","operator":" org运营商名称",
// "assignKeyfob":"4","keyfobId":"5","identificationNumber":"6",
// "authorizedCity":"广州#100（多选）"}
  // "vehicleType":"",
  // "vehicleChassis":"",
  // "assignedId": "",
  // "assignKeyfob": "",
  // "keyfobId": "",
  // "country":"",
  // "plateNumber":"",
  // "color":"",
  // "brandModel":"",
  // "keyfobType":"",
  // "keyfobColor":"",
})
const roleArrOptions = ref([])
const orgOptions = ref([])
const countryAuthorizeOptions = ref([])
const formRules = ref({
  name: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col1'),trigger: 'change'}],
  password: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col2'),trigger: 'change'}],
  mobile: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col3'),trigger: 'change'}],
  // realName: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col4'),trigger: 'change'}],
  // vehicleType: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col5'),trigger: 'change'}],
  status: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col6'),trigger: 'change'}],
  identificationNumber: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col7'),trigger: 'change'}],
  countryAuthorize: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col7'),trigger: 'change'}],
  authorizedCity: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col7'),trigger: 'change'}],
  address: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col7'),trigger: 'change'}],
  assignedId: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col7'),trigger: 'change'}],
  
  // firstName: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col7'),trigger: 'change'}],
  // lastName: [{required: true,message: $T('self.pleaseInput') + $T('self.systemUser.modal.col7'),trigger: 'change'}],

})
const onChangeOrg = (value, option) => {
  // formState.orgName = option.orgName
  formState.value.operator = option.orgName; 
}
const selType = (event) => {
  isAddDisabled.value = event !== 2
}
onMounted(async () => {
  roleArrOptions.value = await proxy.getRoleSelectList()
  orgOptions.value = await proxy.getOrgSelectList(true)
  $API.backend.systemUser.getCountryAuthorize.post().then(res => {
    const { objData } = res
    countryAuthorizeOptions.value = objData.map(ele => {
      return {
        ...ele,
        key: ele.paraDesc + '#' + ele.paraValue + '#' + ele.id
      }
    })
  }).catch(err => {

  })

})

  const africaTestTypeOptions = computed(() => {
    const selectedCountry = formState.value.authorizedCountryCode;
    if (!selectedCountry) return []; 

    const cities = cityRaw[selectedCountry] || [];
    return cities.map(c => ({
      label: `${c.labelCn} / ${c.labelEn}` + (c.labelRW ? ` / ${c.labelRW}` : ''),
      value: `${selectedCountry}_${c.labelEn}`, 
      countryCode: selectedCountry,
      labelCn: c.labelCn,
      labelEn: c.labelEn,
      labelRW: c.labelRW
    }));
	});
	const handleAfricaCountryChange = async (countryCode) => {
		formState.value.authorizedCountryCode = countryCode;
		// formState.value.authorizedCity = null;
		const selectedCountry = africaCountryOptions.find(item => item.value === countryCode);
		formState.value.countryAuthorize = selectedCountry ? selectedCountry.labelEn : null;
	};
	const africaCountryOptions = cityData.africaCountryOptions.map(item => ({
		...item,
		display: `${item.labelCn} / ${item.labelEn}` + (item.labelRW ? ` / ${item.labelRW}` : '')
	}));
	const handleAfricaTestTypeChange = (testType) => {
		formState.value.africaTestType = testType;
		const selectedCity = africaTestTypeOptions.value.find(item => item.value === testType);
		formState.value.authorizedCity = selectedCity ? selectedCity.labelEn : null;
	};
// const getUserInfo = () => {
//   return new Promise((resolve, reject) => {
//     $API.backend.systemUser.queryUserOrgRole.post({
//       id: formState.value.id
//     }).then(res => {
//       const { objData } = res
//       sourceUserInfo.value = objData
//       resolve()
//     }).catch(err => {
//       reject(err)
//     })
//   })
// }

const getDetail = () => {
  return new Promise((resolve, reject) => {
    $API.backend.systemUser.query.post({
      id: formState.value.id
    }).then(res => {
      const { objData } = res
      formState.value.roleIds = objData.roleIdsArr ? objData.roleIdsArr : []

      // const chooseCountryAuthorize = objData.countryAuthorize ? objData.countryAuthorize.split(',') : []

      // formState.value.countryAuthorize = chooseCountryAuthorize.filter(item =>
      //     countryAuthorizeOptions.value.some(option => option.key === item)
      // );

      // formState.value.countryAuthorize = objData.countryAuthorize ? objData.countryAuthorize.split(',') : []

      // console.log('formState', formState.value)
      resolve()
    }).catch(err => {
      message.error(err.msg);
      reject(err)
    })
  })
}

const onSubmit = (values) => {
  const params = { ...formState.value }
  console.log(params)



  params.roleIds = !params.roleIds ? '' : params.roleIds.join(',')
  // params.countryAuthorize = !params.countryAuthorize ? '' : params.countryAuthorize.join(',')
  if(mode.value === 'add') {
    // 添加
    $API.backend.systemUser.add.post(params).then(res => {
      message.success($T('self.message.success'))
      onReset()
      visible.value = false
      emit('ok')
    }).catch(err => {
      message.error(err.msg);
    })
  }else{
    // 修改
    $API.backend.systemUser.edit.post(params).then(res => {
      message.success($T('self.message.success'))
      onReset()
      visible.value = false
      emit('ok')
    }).catch(err => {
      message.error(err.msg);
    })
  }
};

const onReset = () => {
  // 清空内容
  formState.value = {
    "id": 0,
    "userType": 2,
    "realName": "",
    "name": "",
    "password": "",
    "status": 1,
    "mobile": "",
    "orgId": null,
  }
}

const onClose = () => {
  onReset()
  visible.value = false
  emit('close')
}

const add = () => {
  title.value = $T('self.systemUser.tips13')
  mode.value = 'add'
  visible.value = true
}

const edit = async (record) => {
  title.value = $T('self.systemUser.tips14')
  mode.value = 'edit'
  visible.value = true
  formLoading.value = true
  // formState.value = record
  const params = { ...record }
  params.roleIds = params.roleIds ? params.roleIds.split(',') : [] // 在每个逗号(,)处进行分解
  // params.countryAuthorize = [] // 在每个逗号(,)处进行分解
  $TOOL.array.cloneExistKey(formState.value, params)

  // 获取当前用户已经选择的角色
  await getDetail()

  formLoading.value = false
  console.log(formState.value)
}

const show = (record) => {
  mode.value = 'show'
  visible.value = true
  formState.value = record
}

// 子组件中要通过defineExpose将方法暴露给父组件
defineExpose({
  add,
  edit,
  show
})
</script>

<style lang="scss" scoped>
.edit-drawer {
  position: relative;
  .closeable {
    @include closeable;
  }
}
</style>
